<template>
  <el-dialog
    draggable
    overflow
    v-model="visible"
    :title="titleMap[mode]"
    :width="1000"
    destroy-on-close
    @closed="$emit('closed')"
  >
    <sk-tabs type="border-card">
      <el-tab-pane ref="tab" label="基础信息">
        <el-form :model="form" :rules="rules" ref="dialogForm" label-width="70px">
          <el-row>
            <el-col :span="6">
              <el-row justify="space-evenly">
                <el-col :span="22">
                  <el-form-item label="客户">
                    <el-input v-model="form.customer.name" disabled></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="22">
                  <el-form-item label="等级" prop="grade">
                    <el-input v-model="form.grade" disabled></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="22">
                  <el-form-item label="色卡" prop="singler_id">
                    <el-input v-model="form.material.spec" disabled></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="22">
                  <el-form-item label="规格">
                    <el-input v-model="form.material.spec" disabled></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="22">
                  <el-form-item label="产品">
                    <el-input v-model="form.material.name" disabled></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="22">
                  <el-form-item label="批号">
                    <el-input v-model="form.lot.name" disabled></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="22">
                  <el-form-item label="缸号">
                    {{
                      /^[a-zA-Z]$/.test(form.dyelot.charAt(0))
                        ? form.dyelot.slice(1)
                        : form.dyelot
                    }}
                  </el-form-item>
                </el-col>
                <el-col :span="22">
                  <el-form-item label="形态">
                    <el-input v-model="form.type.name" disabled></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="22">
                  <el-form-item label="色号">
                    <el-input v-model="form.color.code" disabled></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="22">
                  <el-form-item label="色名">
                    <el-input v-model="form.color.name" disabled></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="22">
                  <el-form-item label="贸易色号">
                    <el-input v-model="form.color.code_my" disabled></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="22">
                  <el-form-item label="对样人">
                    <el-input v-model="form.color.code_my" disabled></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-col>
            <el-col :span="18">
              <el-row>
                <el-col :span="10">
                  <el-form-item label="单据日期" prop="billdate">
                    <el-date-picker
                      v-model="form.billdate"
                      type="date"
                      placeholder="选择日期"
                      format="YYYY-MM-DD"
                      value-format="YYYY-MM-DD"
                      disabled
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="10">
                  <el-form-item label="申请降级" prop="apply_grade">
                    <el-switch
                      v-model="form.apply_grade"
                      :active-value="1"
                      :inactive-value="0"
                    ></el-switch>
                  </el-form-item>
                </el-col>
                <el-col :span="10">
                  <el-form-item label="库位" prop="location_id">
                    <skAutoChoose
                      v-model="form.location.name"
                      :name="'location'"
                      :assign="form"
                    >
                    </skAutoChoose>
                  </el-form-item>
                </el-col>
                <el-col :span="10">
                  <el-form-item label="售后形态" prop="type_id">
                    <skDicSelect
                      v-model="form.type_id"
                      :code="'type'"
                      :editsource="'default'"
                    >
                    </skDicSelect>
                  </el-form-item>
                </el-col>
                <el-col :span="10">
                  <el-form-item label="售后包数" prop="auxiliary_quantity">
                    <el-input
                      v-model="form.auxiliary_quantity"
                      clearable
                      @keyup="qtybkey"
                    ></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="10">
                  <el-form-item label="售后重量" prop="quantity">
                    <el-input
                      v-model="form.quantity"
                      clearable
                      @keyup="qtykey"
                    ></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="10">
                  <el-form-item label="售后单价" prop="price">
                    <el-input v-model="form.price" clearable @keyup="pricekey"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="10">
                  <el-form-item label="售后金额" prop="amount">
                    <el-input
                      v-model="form.amount"
                      clearable
                      @keyup="amountkey"
                    ></el-input>
                  </el-form-item>
                </el-col>

                <el-col :span="10">
                  <el-form-item label="售后类别" prop="complaint_id">
                    <skDicSelect
                      v-model="form.complaint_id"
                      :code="'Complaint'"
                      :disabled="disabledComplaint"
                    >
                    </skDicSelect>
                  </el-form-item>
                </el-col>

                <el-col :span="10">
                  <el-form-item label="折扣金额" prop="discount">
                    <el-input
                      v-model="form.discount"
                      :disabled="discountdisabled"
                      clearable
                      :placeholder="discountplaceholder"
                    ></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="20">
                  <el-form-item label="备注" prop="remark">
                    <el-input v-model="form.remark" clearable></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-divider>换货/补发才需要选择库存！</el-divider>
              <sc-VxeTable
                ref="save"
                :gridEvts="gridEvts"
                :data="form.details"
                :gridOps="gridOps"
                :tablecode="'market_complaint_save'"
              >
              </sc-VxeTable>
            </el-col>
          </el-row>
        </el-form>
      </el-tab-pane>
      <el-tab-pane label="附件">
        <sk-upload
          v-model="form.attachments"
          :limit="10"
          draggable
          tip="单个文件不要超过10M,请上传图像格式文件"
        >
        </sk-upload>
      </el-tab-pane>
    </sk-tabs>

    <template #footer>
      <el-button @click="visible = false">取 消</el-button>
      <el-button type="primary" :loading="isSaveing" @click="submit()">保 存</el-button>
    </template>
  </el-dialog>

  <skBrowserChoose
    v-model="openChooseDlg"
    :name="'storage_browser'"
    @close="openChooseDlg = false"
    @select="additems"
    :params="{ iscustomer: 0 }"
  >
  </skBrowserChoose>
</template>

<script>
import skBrowserChoose from "@/components/skBrowserChoose";

import skDicSelect from "@/components/skDicSelect";
import skAutoChoose from "@/components/skAutoChoose";
import XEUtils from "xe-utils";
export default {
  emits: ["success", "closed"],
  components: { skAutoChoose, skDicSelect, skBrowserChoose },
  data() {
    return {
      mode: "add",
      openChooseDlg: false,
      gridEvts: {
        choose: () => (this.openChooseDlg = true),
      },
      titleMap: {
        add: "新增",
        edit: "编辑",
      },

      form: {
        id: "",
        billdate: XEUtils.toDateString(new Date(), "yyyy-MM-dd"),
        location: {},
        customer: { name: "" },
        material: {},
        apply_grade: 0,
        lot: {},
        type: {},
        color: {},
        price: 0,
        quantity: 0,
        details: [],
        complaint_id: 2,
        attachments: [],
      },
      rules: {
        billdate: { required: true, message: "请选择单据日期" },
        location_id: { required: true, message: "请选择退货库位" },
        complaint_id: { required: true, message: "请选择售后类别" },
        remark: { required: true, message: "备注必填" },
      },
      visible: false,
      isSaveing: false,
      disabledComplaint: false,
      gridOps: {
        height: 205,
        editRules: {
          price: [{ required: true, message: "单价必填" }],
        },
        columns: [
          {
            field: "auxiliary_quantity",
            event: {
              keyup: ({ row }) => {
                row["amount"] = row["quantity"] * row["price"];
              },
            },
          },
          {
            field: "quantity",
            event: {
              keyup: ({ row }) => {
                row["amount"] = row["quantity"] * row["price"];
              },
            },
          },
          {
            field: "price",
            event: {
              keyup: ({ row }) => {
                row["amount"] = row["quantity"] * row["price"];
              },
            },
          },
          {
            field: "amount",
            event: {
              keyup: ({ row }) => {
                row["price"] = row["amount"] / row["quantity"];
              },
            },
          },
        ],
      },
    };
  },
  computed: {
    discountdisabled() {
      return this.form.complaint_id != 4;
    },
    discountplaceholder() {
      if (this.discountdisabled) {
        return "折价才可以填";
      }
      return "";
    },
    // disabledComplaint() {
    //   return this.form.relation_code == '';
    // }
  },

  watch: {
    "form.price"(val) {
      this.form.amount = this.form.quantity * val;
    },
    "form.quantity"(val) {
      this.form.amount = this.form.price * val;
    },
  },
  mounted() {
    let userInfo = this.$TOOL.data.get("USER_INFO");
    this.form.department_id = userInfo.department_id;
  },
  methods: {
    qtykey() {
      this.form.amount = this.form.quantity * this.form.price;
      this.setSeData();
    },
    qtybkey() {
      this.form.amount = this.form.quantity * this.form.price;
      this.setSeData();
    },
    pricekey() {
      this.form.amount = this.form.quantity * this.form.price;
      this.setSeData();
    },
    amountkey() {
      this.form.price = this.form.amount / this.form.quantity;
      this.setSeData();
    },
    setSeData() {
      this.form.se_price = this.form.price;
      this.form.se_amount = this.form.amount;
      this.form.se_quantity = this.form.quantity;
      this.form.se_amount = this.form.amount;
      this.form.md_quantity = this.form.quantity;
    },
    additems(items) {
      this.openChooseDlg = false;
      items.map(row => {
        delete row.id;
        row["auxiliary_quantity"] = XEUtils.toNumber(row["available_auxiliary_quantity"]);
        row["quantity"] = XEUtils.toNumber(row["available_quantity"]);
        this.form.details.push(row);
        return row;
      });
    },

    //显示
    open(mode = "add") {
      this.mode = mode;
      this.visible = true;
      return this;
    },

    //表单提交方法
    submit() {
      this.$refs.dialogForm.validate(async valid => {
        if (valid) {
          this.isSaveing = true;
          if (this.form.complaint_id != 5) {
            const errMap = await this.$refs.save.xGrid.validate(true);
            if (errMap) {
              this.$message.error("价格必须填写！");
              this.isSaveing = false;
              return;
            }
          }

          var res = await this.$API.market.complaint.save.post(this.form);
          this.isSaveing = false;
          if (res.code == 200) {
            this.$emit("success", this.form, this.mode);
            this.visible = false;
            this.$message.success("操作成功");
          }
        }
      });
    },
    getItems(code) {
      return this.$API.market.complaint.details.post({
        filter: [{ code: code }],
      });
    },
    //表单注入数据
    async setData(data) {
      //售后库存，禁止选择售后类别
      if (data.relation_code == "") {
        this.disabledComplaint = true;
        this.form.complaint_id = 1;
      }

      Object.assign(this.form, this.$TOOL.removeNull(data));
      this.form.customer_id = data.main_customer_id ?? data.customer_id;
      console.log(this.form);
      if ((this.form.code ?? "") != "")
        this.getItems(this.form.code).then(res => {
          if (res.code == 200) this.form.details = res.data;
        });
    },
  },
};
</script>
